<?php

namespace App\Http\Controllers;

use App\Models\Form;
use App\Models\FormSubmit;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FormController extends Controller
{


    /**
     * 前端表单提交
     * @param Request $request
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function submit(Request $request){
        $this->validate($request, [
            'subId'  => 'string',
            'formId' => 'required',
            'data'    => 'array|required'
        ]);
        $formId = $request->get('formId');
        $form = Form::whereFormId($formId)->first();
        if(!$form){
            return self::error('表单不存在');
        }
        $subId = $request->get('subId');
        if(FormSubmit::whereFormId($formId)->whereSubId($subId)->exists()){
            return self::error('您已提交过该表单, 请勿重复提交.');
        }
        $data = $request->get('data');
        $inserted = [];
        $subId = md5(time() + rand(0, 1000000));
        foreach ($data as $field){
            $fieldId = $field['field'];
            $fieldName = $field['label'];
            $options   = isset($field['options']) ? array_map(function($option){
                return $option['label'];
            }, $field['options']) : [];
            $value = $field['value'];
            //如果是选项, 那么需要遍历处理选项
            if($options){
                //如果是多选想
                if(is_array($value)){
                    $value = array_map(function($index) use ($options){
                        return $options[$index];
                    }, $value);
                }
                //否则是单选
                else{
                    $value = $options[$value];
                }
            }
            //重复性校验
            if(isset($field['repeatCheck']) && $field['repeatCheck'] && $value){
                $exist = FormSubmit::whereFormId($formId)->whereFieldName($fieldId)->whereFieldValue($value)->exists();
                if($exist){
                    return self::error('已存在该'.$fieldName.', 不能重复提交');
                }
            }
            $submit = new FormSubmit();
            $submit->form_id = $formId;
            $submit->field_name = $fieldId;
            $submit->sub_id  = $subId;
            $submit->field_value = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
            $inserted[] = $submit;
        }
        try{
            DB::transaction(function() use ($inserted){
                foreach ($inserted as $insertedItem){
                    $insertedItem->save();
                }
            });
            return self::success(['sub_id' => $subId]);
        }catch (\Exception $e){
            return self::error($e->getMessage());
        }
    }


    /**
     * 根据网站SqId 获取网站的表单列表
     * @param Request $request
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function listByPageSqId(Request $request){
        $this->validate($request, [
            'page_sq_id' => 'required'
        ]);
        $forms = Form::wherePageSqId($request->get('page_sq_id'))->get();
        return self::success($forms);
    }


    /**
     * @param Request $request
     * @return array
     * @throws \Illuminate\Validation\ValidationException
     */
    public function dataByFormId(Request $request){
        $this->validate($request, [
            'form_id' => 'required',
            'last_id'    => 'integer',
            'page_size' => 'required|integer'
        ]);
        $formId = $request->get('form_id');
        $query = FormSubmit::query()->whereFormId($formId)->select(['id', 'sub_id'])->orderBy('id','desc')->groupBy('sub_id');
        $lastId = $request->get('last_id');
        if($lastId){
            $query->where('id', '<', $lastId);
        }
        $pageSize = $request->get('page_size');
        $pageSize = $pageSize > 50 || $pageSize < 0 ? 20 : $pageSize;
        $submitGroups = $query->limit($pageSize)->get();
        $subIds   = $submitGroups->map(function (FormSubmit $formSubmit){
            return $formSubmit->sub_id;
        })->toArray();
        if(!$subIds){
            return self::success([]);
        }
        $submits = FormSubmit::whereIn('sub_id', $subIds)->orderBy('id', 'desc')->get();
        $data    = $submits->groupBy('sub_id')->values();
        $data = $data->map(function (Collection $formSubmits){
            return $formSubmits->reduce(function ($initial, FormSubmit $formSubmit){
                if($formSubmit->field_name){
                    $initial['key'] = $formSubmit->id;
                    $initial[$formSubmit->field_name] = $formSubmit->field_value;
                }
                return $initial;
            }, []);
        });
        return self::success($data);
    }
}
